<!--
 * @Description: 登录界面
 * @Author: 翟磊
 * @Date: 2023-12-21 10:31:48
-->
<template>
  <div class="login-container" :style="backgroundImage">
    <!-- <div class="login-title">
      <div class="logo" :style="loginLogo"></div>
      <div class="title"></div>
    </div> -->
    <div class="login-authorization">
      <div class="sub-title">欢迎登录</div>
      <div class="authorization-body">
        <a-form-model :model="form">
          <a-form-model-item class="">
            <div class="account-icon" :class="[accountIcon && 'active']"></div>
            <a-input
              v-model.trim="form.userNameId"
              placeholder="请输入账号"
              allowClear
              autocomplete="off"
              @focus="handleFocus($event, 'account')"
              @blur="handleBlur($event, 'account')"
            />
          </a-form-model-item>
          <a-form-model-item>
            <div
              class="password-icon"
              :class="[passwordIcon && 'active']"
            ></div>
            <a-input-password
              v-model.trim="form.password"
              placeholder="请输入密码"
              allowClear
              autocomplete="off"
              @focus="handleFocus($event, 'password')"
              @blur="handleBlur($event, 'password')"
            />
          </a-form-model-item>
          <a-row :gutter="10">
            <a-col :span="16">
              <a-form-model-item class="m-18">
                <div class="code-icon" :class="[codeIcon && 'active']"></div>
                <a-input
                  placeholder="请输入验证码"
                  allowClear
                  autocomplete="off"
                  v-model.trim="form.code"
                  @focus="handleFocus($event, 'code')"
                  @blur="handleBlur($event, 'code')"
                >
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item class="m-18">
                <div class="code-img" @click="getCode()">
                  <img
                    v-if="requestCodeSuccess"
                    :contentWidth="90"
                    :src="identifyCode"
                    title="看不清?点击切换"
                  />
                  <img v-else src="~@/assets/img/code.png" alt="" />
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div class="remember">
          <a-checkbox v-model.trim="rememberPassword">记住密码</a-checkbox>
          <!-- <div class="forget">忘记密码?</div> -->
        </div>
      </div>
      <a-button
        class="authorization-footer"
        :loading="loginBtn"
        :disabled="loginBtn"
        @click="login()"
        @keyup.enter="keyDown(e)"
      >
        登录
      </a-button>
    </div>
    <div class="login-copyright">
      {{ copyright }} {{ companyName }} 版权所有
      <!-- <span @click="viewForRecord()">苏ICP备07020600号-2</span> -->
    </div>
  </div>
</template>

<script>
import { getSystemConfig } from "@/utils/TopVUI.js";
import { JSEncrypt } from "jsencrypt";
import { mapActions, mapGetters } from "vuex";
import { releaseEngine, restEngine } from "@/blackHoleTools/Engine.js";
export default {
  name: "LoginContent",
  data() {
    return {
      form: {
        //账号
        userNameId: "",
        //密码
        password: "",
        //验证码
        code: "",
      },
      loginBtn: false,
      isLoginError: false,
      rememberPassword: true,
      //图形验证码
      requestCodeSuccess: false,
      identifyCode: "",
      //
      accountIcon: false,
      passwordIcon: false,
      codeIcon: false,
    };
  },
  computed: {
    ...mapGetters(["addRouters"]),
    //背景图
    backgroundImage() {
      let bgImg = getSystemConfig("bgImg");
      if (bgImg) {
        return { backgroundImage: "url(" + bgImg + ")" };
      }
    },
    //logo
    loginLogo() {
      let logo = getSystemConfig("loginLogo");
      if (logo) {
        return { backgroundImage: "url(" + logo + ")" };
      }
    },
    //底部公司名称
    companyName() {
      return getSystemConfig("companyName") || "上海建科工程咨询有限公司";
    },
    //底部版权
    copyright() {
      return getSystemConfig("copyright") || "";
    },
  },
  created() {
    //浏览器标题
    document.title = getSystemConfig("systemName") || "数字项目管理平台";
    //
    localStorage.clear();
    sessionStorage.clear();
    this.clearCookies();
    releaseEngine();
    restEngine();
    this.getCode();
  },
  mounted() {
    window.addEventListener("keydown", this.keyDown);
  },
  methods: {
    handleFocus(e, type) {
      switch (type) {
        case "account":
          this.accountIcon = true;
          break;
        case "password":
          this.passwordIcon = true;
          break;
        case "code":
          this.codeIcon = true;
          break;
        default:
          break;
      }
    },
    handleBlur(e, type) {
      switch (type) {
        case "account":
          this.accountIcon = false;
          break;
        case "password":
          this.passwordIcon = false;
          break;
        case "code":
          this.codeIcon = false;
          break;

        default:
          break;
      }
    },

    ...mapActions(["Login"]),

    clearCookies() {
      var cookies = document.cookie.split("; ");
      for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
      }
    },

    //回车登录事件
    keyDown(e) {
      if (e.key == "Enter" && this.$route.name == "login") {
        this.login();
      }
    },

    //登录
    login() {
      let { Login, form } = this;
      let { userNameId, password, code } = form;
      if (!userNameId) {
        this.$message.error("请输入账号！");
        return;
      } else if (!password) {
        this.$message.error("请输入密码！");
        return;
      } else if (!code) {
        this.$message.error("请输入图形验证码！");
        return;
      }
      this.loginBtn = true;
      let loginParams = { ...form };
      let publicKey =
        "-----BEGIN PUBLIC KEY-----\n" +
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5bxAa8KASxYwrRe7kP8XjF8LO\n" +
        "pbAqDVj3HZEu+j/8zp75TRYXnOeNFV4QjPktsvTI0ErtH2Bzvkedkhm5JQYxQ/yv\n" +
        "nGMtbvV3VNkaKtT+fVYtBN5bF1IXJP5YLR/IvevMx5h3WqTiwZG4Df/QJ0Abenl6\n" +
        "GUfXZi0aR85+ysc6UwIDAQAB\n" +
        "-----END PUBLIC KEY-----";
      let encryptor = new JSEncrypt(); // 新建JSEncrypt对象
      let loginPasswd = this.$md5(loginParams.password); // 对密码进行加密
      //在本地存储
      localStorage.setItem("loginPasswd", loginPasswd);
      encryptor.setPublicKey(publicKey); // 设置公钥
      let rsaPassWord = encryptor.encrypt(loginParams.password); // 对密码进行加密
      loginParams.password = rsaPassWord;
      Login(loginParams)
        .then((res) => this.loginSuccess(res))
        .catch((err) => this.requestFailed(err))
        .finally((_) => {
          // 延迟 1 秒显示欢迎信息
          setTimeout(() => {
            this.loginBtn = false;
          }, 1000);
        });
    },

    //登陆成功 /system/portal/index
    loginSuccess(res) {
      this.getLanguageMap();
      let { firstLogin } = res;
      switch (Number(firstLogin)) {
        //首次登录进入修改密码页面
        case 0:
          this.$router.push({
            path: "/firstPassword",
          });
          break;
        //进入系统
        default:
          this.$router.push({
            path: "/excessive",
          });
          break;
      }
    },

    //登陆失败
    requestFailed(err) {
      this.form.code = "";
      this.getCode();
      this.loginBtn = false;
      this.$message.error(err.message);
    },

    //获取图形验证码
    getCode() {
      let that = this;
      that
        .$post("/system/getVerificationImg.api")
        .then((res) => {
          if (200 == res.statusCode) {
            let { message } = res;
            that.form.code == "";
            that.identifyCode = message;
            that.requestCodeSuccess = true;
          } else {
            that.requestCodeSuccess = false;
          }
        })
        .catch(() => {
          this.requestCodeSuccess = false;
        });
    },

    // 获取多语言数据
    getLanguageMap() {
      this.$post("/system/sysLanguage/getLanguageMap").then((langRes) => {
        if (langRes.statusCode === 200) {
          let langData = langRes.data;
          this.$post("/system/sysLanguageConfig/selectAll").then((typeRes) => {
            let langTypeData = [];
            if (typeRes.statusCode === 200) {
              langTypeData = typeRes.data.map((e) => e.configValue);
            }
            let langTypeMap = {};
            for (let i = 0; i < langTypeData.length; i++) {
              let langDataMap = {};
              for (let key in langData) {
                if (key.indexOf("_" + langTypeData[i]) >= 0) {
                  langDataMap[key.replace("_" + langTypeData[i], "")] =
                    langData[key];
                  langTypeMap[langTypeData[i]] = langDataMap;
                }
              }
              this.$i18n.setLocaleMessage(
                langTypeData[i],
                langTypeMap[langTypeData[i]]
              );
            }
          });
        }
      });
    },

    //跳转备案系统查询
    viewForRecord() {
      window.open("https://beian.miit.gov.cn/#/Integrated/index");
    },
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyDown);
  },
};
</script>

<style lang="less">
@import "./login.less";
</style>
